package com.changgou.system.filter;

import com.changgou.system.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired
    AuthService authService;
    @Autowired
    private RedisTemplate redisTemplate;

    private static final String LOGIN_URL = "http://localhost:8080/#/login";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //1.路径是否为登录请求,是则放行
        String path = request.getURI().getPath();
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        HttpCookie remark_token = cookies.getFirst("remark_token");
        if (remark_token!=null){
            String value = remark_token.getValue();
            Map roken = (Map) redisTemplate.boundValueOps(value).get();
            if (roken==null) {
                if (path.contains("addComment")){
                    //跳转到登录界面
                    return this.toLoginPage(LOGIN_URL+"?FROM="+request.getURI(),exchange);
                }
            }else {
                String login = (String) roken.get("login");
                if (login==null) {
                    if (path.contains("addComment")){
                        //跳转到登录界面
                        return this.toLoginPage(LOGIN_URL+"?FROM="+request.getURI(),exchange);
                    }
                }else {
                    request.mutate().header("user",login);
                }
            }

        }
        if (path.contains("addComment")){
            //跳转到登录界面
            return this.toLoginPage(LOGIN_URL+"?FROM="+request.getURI(),exchange);
        }
        return chain.filter(exchange);
    }

    //跳转登录界面
    private Mono<Void> toLoginPage(String loginUrl, ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.SEE_OTHER);
        response.getHeaders().set("Location", loginUrl);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
